import type { Ref } from "vue";
import type { DeptDetailResult } from "@/api/types";
import type { DeptTreeExpose } from "@/components/ReCommon/src/tree/deptTree";
import { ref } from "vue";
import { deptApi } from "@/api";

interface UseDeptTree {
    /** 树组件引用 */
    deptTreeRef: Ref<DeptTreeExpose | null>;
    /** 当前选中的部门 */
    deptData: Ref<DeptDetailResult | null>;
    /** 处理树节点点击事件 */
    nodeClick: (data: DeptDetailResult, callback?: () => void) => void;
    /** 在树中移除节点 */
    removeNodeFromTree: (code: string) => void;
    /** 在树中添加新节点 */
    addNodeToTree: (id: string, treeRef: DeptTreeExpose | null, callback?: () => void) => Promise<void>;
    /** 在树中更新节点 */
    updateNodeInTree: (id: string, treeRef: DeptTreeExpose | null, callback?: (deptData: DeptDetailResult) => void) => Promise<void>;
}

export function useDeptTree(): UseDeptTree {
    const deptTreeRef = ref<DeptTreeExpose | null>(null);
    const deptData = ref<DeptDetailResult | null>(null);

    function nodeClick(data: DeptDetailResult, callback?: () => void): void {
        if (deptData.value?.id === data.id) return; // 避免重复加载
        deptData.value = data;
        callback?.();
    }

    function removeNodeFromTree(code: string): void {
        const tree = deptTreeRef.value?.innerTreeRef;
        if (tree) {
            tree.remove({ code });
        }
    }

    /** 在树中添加新节点 */
    async function addNodeToTree(
        id: string,
        treeRef: DeptTreeExpose | null,
        callback?: () => void,
    ): Promise<void> {
        const depart = (await deptApi.findById(id)).data;
        const nodeKey = depart?.code.split(".").slice(0, -1).join(".");
        const tree = treeRef?.innerTreeRef;
        if (tree && depart && nodeKey) {
            const parentNode = tree.getNode(nodeKey);
            if (parentNode) {
                tree.append(depart, parentNode);
                callback?.();
            }
        }
    }

    /** 在树中更新节点 */
    async function updateNodeInTree(
        id: string,
        treeRef: DeptTreeExpose | null,
        callback?: (deptData: DeptDetailResult) => void,
    ): Promise<void> {
        const depart = (await deptApi.findById(id)).data;
        const tree = treeRef?.innerTreeRef;
        if (tree && depart) {
            const node = tree.getNode(depart.code);
            if (node) {
                Object.assign(node.data, depart); // 更新节点数据
                callback?.(depart);
            }
        }
    }

    return {
        deptTreeRef,
        deptData,
        nodeClick,
        removeNodeFromTree,
        addNodeToTree,
        updateNodeInTree,
    };
}
